package bookManager.daoImpl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import bookManager.dao.BookDao;
import bookManager.po.Book;
import util.dbUtil.DbUtil;



public class BookDaoImpl implements BookDao {
//	SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

	// Date date = formatter.parse(s);



	@Override
	public int addBook(Book b) {
		String sql = "insert into springbooks (id,bname,price,pressdate) values (spring_book_seq01.nextval,?,?,?)";
		Connection con = null;
		PreparedStatement pst = null;
		con = DbUtil.connect();
		int m = 0;
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, b.getBname());
			pst.setDouble(2, b.getPrice());
			pst.setDate(3, new Date((b.getPressDate()).getTime()));
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}

		return m;
	}

	@Override
	public int deleteBook(int id) {
		String sql = "delete from books where id=?";
		Connection con = null;
		PreparedStatement pst = null;
		con = DbUtil.connect();
		int m = 0;
		try {
			pst = con.prepareStatement(sql);
			pst.setInt(1, id);

			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}
		return m;
	}

	@Override
	public List<Book> findAllBooks() {
		List<Book> bks = new ArrayList<Book>();

		String sql = "select * from springbooks";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();
		try {
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			while (rs.next()) {
				int id = rs.getInt("id");
				String bname = rs.getString("bname");
				double price = rs.getDouble("price");
				Date pressDate1=rs.getDate("pressdate");
				java.util.Date pressDate=new java.util.Date(pressDate1.getTime());

				Book bk = new Book(bname, price, pressDate);
				bk.setId(id);

				bks.add(bk);
			}
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}
		return bks;
	}

}
